package com.example.managesystem.service.impl;

import com.example.managesystem.context.BaseContext;
import com.example.managesystem.dto.*;
import com.example.managesystem.entity.*;
import com.example.managesystem.exception.BaseException;
import com.example.managesystem.mapper.*;
import com.example.managesystem.service.ItemService;
import com.example.managesystem.vo.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserItemRelaMapper userItemRelaMapper;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private SetItemFailureMapper setItemFailureMapper;
    @Autowired
    private  MidItemFailureMapper midItemFailureMapper;
    @Autowired
    private CompeletedItemFailureMapper compeletedItemFailureMapper;
    @Autowired
    private DelayItemMapper delayItemMapper;
    @Autowired
    private  AchievementMapper achievementMapper;
    @Autowired
    private  TimeMapper timeMapper;


    /**
     * 项目申报
     * @param
     * @param postItemDTO
     */
    @Transactional
    public void saveItem(PostItemDTO postItemDTO) {
        log.info("项目申报");
        Item item = new Item();
        BeanUtils.copyProperties(postItemDTO,item);

        itemMapper.saveItem(item);
        log.info("项目id为：{}",item.getItemId());
        Integer itemId = item.getItemId();
        itemMapper.updateStatusByItemId(itemId);


        //遍历用户集合
        //修改用户表 修改用户 项目关系表
        List<User> users = postItemDTO.getUsers();
        for(int i=0;i<users.size();i++){
            if(i==0){
                User user1 = users.get(i);
                log.info("用户id为：{}",user1.getUserid());
                //修改项目表当中 prinuserid字段
                itemMapper.updatePrinuseridByItemId(itemId,user1.getUserid());
                //修改用户表
                log.info("用户信息为：{}",user1);
                userMapper.updateMessage(user1);
                //修改关系表
                log.info("用户关系信息为：{}",user1);
                userItemRelaMapper.insertUserItem(user1.getUserid(),item.getItemId(),i,user1.getWork());
            } else if (i== users.size()-1) {
                User user1 = users.get(i);
                //修改项目表当中 conduserid字段
                itemMapper.updateConduseridByItemId(itemId,user1.getUserid());
                log.info("用户id为：{}",user1.getUserid());

                userMapper.updateMessage(user1);
                userItemRelaMapper.insertUserItem(user1.getUserid(),item.getItemId(),3,user1.getWork());
            } else if (i== users.size()-2) {
                User user1 = users.get(i);
                log.info("用户id为：{}",user1.getUserid());

                userMapper.updateMessage(user1);
                userItemRelaMapper.insertUserItem(user1.getUserid(),item.getItemId(),3,user1.getWork());
            } else{
                User user1 = users.get(i);
                log.info("用户id为：{}",user1.getUserid());
                userMapper.updateMessage(user1);
                userItemRelaMapper.insertUserItem(user1.getUserid(),item.getItemId(),2,user1.getWork());
            }

        }

        String setupTime = timeMapper.getSetupStartTime(1);
        String date = new Date().toString();
        if (setupTime.compareTo(date)>0){
            throw new BaseException("申报时间未到，不能申报项目");
        }




    }

    /**
     * 查看项目细节详情
     * @param itemId
     * @return
     */
    @Override
    public PostItemVO lookItemDetails(Integer itemId) {
        //构建传出对象
        PostItemVO postItemVO = new PostItemVO();
        //获取项目信息
        Item item = itemMapper.getItemByItemId(itemId);
        BeanUtils.copyProperties(item,postItemVO);

        List<UserMainVO> userMainVOs = new java.util.ArrayList<>();
        List<FileMainVO> fileMainVOs = new java.util.ArrayList<>();



        //获取项目下的所有成员的userid
        List<String> userids = userItemRelaMapper.getUseridsByItemId(itemId);
        //输出userid集合
        log.info(userids.toString());

        for(int i=0;i<userids.size();i++){
            UserMainVO userMainVO = new UserMainVO();
            //获取到项目下的第一个成员的user对象 是负责人
            if(i==0){
                //获取到项目下的第一个成员的user对象 是负责人
                log.info("项目下的第一个成员的userid为："+userids.get(i));
                User user=userMapper.getByUserId(userids.get(i));
                BeanUtils.copyProperties(user,userMainVO);
                String work = userItemRelaMapper.getWorkByItemidWithUserid(itemId, userids.get(i));
                userMainVO.setWork(work);
                userMainVOs.add(userMainVO);
            } else if (i>=userids.size()-2) {
                //获取到项目下的最后两个个成员的user对象 是指导老师
                log.info("项目下的最后两个个成员的userid为 是指导老师："+userids.get(i));
                User user=userMapper.getByUserId(userids.get(i));
                BeanUtils.copyProperties(user,userMainVO);
                String work = userItemRelaMapper.getWorkByItemidWithUserid(itemId, userids.get(i));
                userMainVO.setWork(work);
                userMainVOs.add(userMainVO);
            }else{
                //获取到项目下的其他成员的user对象 是成员
                log.info("项目下的其他成员的userid为："+userids.get(i));
                User user=userMapper.getByUserId(userids.get(i));
                BeanUtils.copyProperties(user,userMainVO);
                String work = userItemRelaMapper.getWorkByItemidWithUserid(itemId, userids.get(i));
                userMainVO.setWork(work);
                userMainVOs.add(userMainVO);
            }

        }
        postItemVO.setUserMainVOs(userMainVOs);
        log.info("找到项目下的附件");
        List<Integer> fileIds = itemMapper.getFileIdByitemId(itemId);
        for (int i = 0; i < fileIds.size(); i++) {
            FileMainVO fileMainVO = new FileMainVO();
            Integer fileId = fileIds.get(i);
            File file = fileMapper.getFileByFileId(fileId);
            BeanUtils.copyProperties(file,fileMainVO);
            fileMainVOs.add(fileMainVO);
        }
        postItemVO.setFileMainVOs(fileMainVOs);



        return postItemVO;
    }

    /**
     * 查看项目进展记录
     * @return
     */
    @Override
    public ItemsProgressVO lookItemsProgress() {
        log.info("查看项目进展记录");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)

        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        ItemsProgressVO itemsProgressVO=new ItemsProgressVO();
        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("立项")) {
                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师的名字
                ItemProgressVO itemProgressVO = itemMapper.getProgressByItemId(itemId);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                itemProgressVO.setPrinName(prinName);
                itemProgressVO.setCondName(condName);
                log.info("输出查询到的项目信息：{}", itemProgressVO);
                itemsProgressVO.add(itemProgressVO);
            }
        };

        return itemsProgressVO;
    }

    @Override
    public SetItemFailureVO setItemFailure(Integer itemId) {

        SetItemFailureVO setItemFailureVO = itemMapper.getSetItemFailureByItemId(itemId);
        // 往失败详情信息里加入 负责人和指导教师的名字
        String conduserid = setItemFailureVO.getConduserid();
        String condName = userMapper.getNameByUserId(conduserid);
        log.info("指导老师为：{}",condName);
        setItemFailureVO.setCondName(condName);
        String prinuserid = setItemFailureVO.getPrinuserid();
        String prinName = userMapper.getNameByUserId(prinuserid);
        log.info("负责人为：{}",prinName);
        setItemFailureVO.setPrinName(prinName);
        // 查询立项失败详情表 当中关于本项目的立项失败信息
        String reason =setItemFailureMapper.getReason(itemId);
        setItemFailureVO.setReason(reason);
        log.info("项目id为：{}",itemId);

        return setItemFailureVO;
    }

    /**
     * 获取中期检查项目
     * @return
     */
    @Override
    public MidItermsVO getMidterm() {
        log.info("获取中期检查项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)

        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息

        MidItermsVO midItermsVO = new MidItermsVO();


        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("中期")){

            MidItermVO midItermVO = new MidItermVO();
            //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师的名字和项目下的所有成员
            Item item = itemMapper.getItemByItemId(itemId);
            BeanUtils.copyProperties(item,midItermVO);

            //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
            String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
            String conduserid = itemMapper.getConduseridByItemId(itemId);
            String prinName = userMapper.getNameByUserId(prinuserid);
            String condName = userMapper.getNameByUserId(conduserid);
            midItermVO.setPrinName(prinName);
            midItermVO.setCondName(condName);
            log.info("输出查询到的项目信息：{}",midItermVO);
            //现在去 用户 项目关系表中找到该项目下的所有成员
            List<String> userids= userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
            List<String> names=new ArrayList<>();
             for (String userid1:userids){
                 names.add(userMapper.getNameByUserId(userid1));
             }
            midItermVO.setNames(names);
             log.info("输出查询到的项目信息：{}",midItermVO);
            midItermsVO.add(midItermVO);
           }
        };
        // 可以下载的附件
        List<FileVO> files=new ArrayList<>();
        FileVO fileVO1 = fileMapper.getFileUrlByFileid(1);
        FileVO fileVO2 = fileMapper.getFileUrlByFileid(2);
        files.add(fileVO1);
        files.add(fileVO2);
        midItermsVO.setFiles(files);


        return midItermsVO;
    }

    /**
     * 提交中期检查报告
     * @param itemId
     * @return
     */
    @Transactional
    @Override
    public SubmitMidtermPaperVO submitMiditemPaper(Integer itemId) {
        log.info("提交中期检查报告");
        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        SubmitMidtermPaperVO submintMidtermPaperVO = new SubmitMidtermPaperVO();
        BeanUtils.copyProperties(item,submintMidtermPaperVO);
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        submintMidtermPaperVO.setCondName(condName);
        submintMidtermPaperVO.setPrinName(prinName);

        String midItemTime = timeMapper.getMiditemStartTime(1);
        String date = new Date().toString();
        if (midItemTime.compareTo(date)>0){
            throw new BaseException("中期开始时间已经过了 提交中期报告失败");
        }
        return submintMidtermPaperVO;
    }

    /**
     * 查看中期检查项目失败详情
     */
    @Override
    public SubmitMidtermFailureVO LookMiditemFailure(Integer itemId) {
        log.info("查看中期检查项目失败详情");
        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        SubmitMidtermFailureVO submitMidtermFailureVO = new SubmitMidtermFailureVO();
        BeanUtils.copyProperties(item,submitMidtermFailureVO);
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        submitMidtermFailureVO.setCondName(condName);
        submitMidtermFailureVO.setPrinName(prinName);
        //查看项目中期失败原因
        String reason=midItemFailureMapper.LookFailureReason(itemId);
        submitMidtermFailureVO.setReason(reason);
        return submitMidtermFailureVO;

    }

    /*
    * 查看中期检查项目修改成员信息
     */
    @Override
    public MidItemUpdatePeopleMessageVO LookMiditemUpdatePeopleMessage(Integer itemId) {
        log.info("查看中期检查项目修改成员信息");
        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        MidItemUpdatePeopleMessageVO midItemUpdatePeopleMessageVO = new MidItemUpdatePeopleMessageVO();
        BeanUtils.copyProperties(item,midItemUpdatePeopleMessageVO);
        //查询关于负责任的基本信息
        String prinuserid = item.getPrinuserid();
        User user = userMapper.getByUserId(prinuserid);
        midItemUpdatePeopleMessageVO.setPrinName(user.getName());
        midItemUpdatePeopleMessageVO.setPrinDept(user.getDept());
        midItemUpdatePeopleMessageVO.setPrinMajor(user.getMajor());
        midItemUpdatePeopleMessageVO.setPrinuserid(user.getUserid());
        String work = userItemRelaMapper.getWorkByItemidWithUserid(itemId, prinuserid);
        midItemUpdatePeopleMessageVO.setPrinWork(work);
        midItemUpdatePeopleMessageVO.setPrinPhone(user.getPhone());
        return midItemUpdatePeopleMessageVO;
    }

    @Override
    public CompeletedItermsVO CompeletedIterms() {
        log.info("获取需要终项审核项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)

        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        CompeletedItermsVO compeletedItermsVO=new CompeletedItermsVO();


        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            log.info("开始遍历每一个项目id{}",itemId);
            String itemStatus = itemMapper.getItemStatus(itemId);
            if (itemStatus.contains("结项")) {
                CompeletedItermVO compeletedItermVO = new CompeletedItermVO();
                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师的名字和项目下的所有成员
                Item item = itemMapper.getItemByItemId(itemId);
                BeanUtils.copyProperties(item, compeletedItermVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                compeletedItermVO.setPrinName(prinName);
                compeletedItermVO.setCondName(condName);
                log.info("输出查询到的项目信息：{}", compeletedItermVO);
                //现在去 用户 项目关系表中找到该项目下的所有成员
                List<String> userids = userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
                List<String> names = new ArrayList<>();
                for (String userid1 : userids) {
                    names.add(userMapper.getNameByUserId(userid1));
                }
                compeletedItermVO.setNames(names);
                compeletedItermsVO.add(compeletedItermVO);
            }
            };
        List<FileVO> files = new ArrayList<>();
        FileVO fileVO3=fileMapper.getFileUrlByFileid(3);
        FileVO fileVO4=fileMapper.getFileUrlByFileid(4);
        FileVO fileVO5=fileMapper.getFileUrlByFileid(5);
        FileVO fileVO6=fileMapper.getFileUrlByFileid(6);
        files.add(fileVO3);
        files.add(fileVO4);
        files.add(fileVO5);
        files.add(fileVO6);
        compeletedItermsVO.setFiles(files);
        return compeletedItermsVO;

    }

    /**
     * 查看项目终项审核失败详情
     * @param itemId
     * @return
     */
    @Override
    public SubmitCompeletedItemFailureVO LookCompeletedFailure(Integer itemId) {
        log.info("查看结项项目审核失败详情");
        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        SubmitCompeletedItemFailureVO submitCompeletedItemFailureVO=new SubmitCompeletedItemFailureVO();

        BeanUtils.copyProperties(item,submitCompeletedItemFailureVO);
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        submitCompeletedItemFailureVO.setCondName(condName);
        submitCompeletedItemFailureVO.setPrinName(prinName);
        //查看项目终项失败原因
        String reason=compeletedItemFailureMapper.LookFailureReason(itemId);
        submitCompeletedItemFailureVO.setReason(reason);

        return submitCompeletedItemFailureVO;

    }

    /**
     * 项目终项审核 补充材料
     * @param itemId
     * @return
     */
    @Transactional
    @Override
    public SubmitComitemPaperVO submitComitemPaper(Integer itemId) {
        log.info("项目终项审核 补充材料");

        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        SubmitComitemPaperVO submintComitemPaperVO = new SubmitComitemPaperVO();

        BeanUtils.copyProperties(item,submintComitemPaperVO );
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        submintComitemPaperVO .setCondName(condName);
        submintComitemPaperVO.setPrinName(prinName);

        String completedStartTime = timeMapper.getCompletedStartTime(1);
        String date = new Date().toString();
        if (completedStartTime.compareTo(date)>0){
            throw new BaseException("结项开始时间已经过了 提交结项材料失败");
        }
        return submintComitemPaperVO;

    }

    /**
     * 准备延期结项申请
     * @param
     * @return
     */
    @Override
    public PrepareDelayitemVO prepareDelayitem(Integer itemId) {
        log.info("准备延期结项申请");
        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        PrepareDelayitemVO prepareDelayitem=new PrepareDelayitemVO();

        BeanUtils.copyProperties(item, prepareDelayitem );
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        prepareDelayitem .setCondName(condName);
        prepareDelayitem.setPrinName(prinName);
        return  prepareDelayitem;
    }

    /**
     * 提交延期结项申请
     * @param itemId
     * @param reason
     */
    @Override
    public void submitDelayitem(Integer itemId, String reason) {
        delayItemMapper.insertDelayItem(itemId,reason);

    }

    @Override
    public DelayItemDetailVO LookDelayitemDetail(Integer itemId) {
        log.info("查看延期申请详情");
        log.info("查看结项项目审核失败详情");
        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        DelayItemDetailVO delayItemDetailVO=new DelayItemDetailVO();


        BeanUtils.copyProperties(item,delayItemDetailVO);
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        delayItemDetailVO.setCondName(condName);
        delayItemDetailVO.setPrinName(prinName);
        //查看项目申请延期结项 用户提交的申请原因

        String reason=delayItemMapper.LookSubmitDelayReason(itemId);
        delayItemDetailVO.setReason(reason);

        return delayItemDetailVO;

    }

    /**
     * 结项审核 准备补交材料的信息展示
     * @param itemId
     * @return
     */
    @Override
    public PrepareSubmitMaterialVO prepareSubmitMaterial(Integer itemId) {
        log.info("结项审核 准备补交材料的信息展示");

        //拷贝基本信息 以及项目的开始时间和结束时间
        Item item = itemMapper.getItemByItemId(itemId);
        PrepareSubmitMaterialVO prepareSubmitMaterial=new PrepareSubmitMaterialVO();
        BeanUtils.copyProperties(item,prepareSubmitMaterial);

        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        prepareSubmitMaterial.setCondName(condName);
        prepareSubmitMaterial.setPrinName(prinName);
        //查看项目对应的成员有哪些 遍历这些成员 获取对应的userid 和name
        List<UserNameAndUserid> peoples=new ArrayList<>();
        List<String> userids = userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
        for (String userid : userids) {
            UserNameAndUserid userNameAndUserid = new UserNameAndUserid();
            User user = userMapper.getByUserId(userid);
            userNameAndUserid.setId(user.getId());
            userNameAndUserid.setUserid(userid);
            userNameAndUserid.setName(user.getName());
            peoples.add(userNameAndUserid);
        }
        prepareSubmitMaterial.setUsers(peoples);
        return prepareSubmitMaterial;
    }

    /**
     * 提交材料
     * @param
     * @return
     */
    @Override
    public void submitMaterial(SubmitMatrialDTO submitMatrialDTO) {
        log.info("Service层提交材料");
        Achievement achievement = new Achievement();
        BeanUtils.copyProperties(submitMatrialDTO,achievement);
        achievementMapper.insertAchievement(achievement);
    }

    @Override
    public ExamineSetupItemsVO getExamineSetupItems() {
        log.info("获取需要进行审核立项申请的项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)
        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        ExamineSetupItemsVO examineSetupItemsVO=new ExamineSetupItemsVO();

        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("立项")) {
                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师信息
                log.info("开始遍历每一个项目id{}", itemId);
                Item item = itemMapper.getItemByItemId(itemId);
                ExamineSetupItemVO examineSetupItemVO = new ExamineSetupItemVO();
                BeanUtils.copyProperties(item, examineSetupItemVO);

                log.info("输出查询到的项目信息：{}", examineSetupItemVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                examineSetupItemVO.setPrinName(prinName);
                examineSetupItemVO.setCondName(condName);

                log.info("输出查询到的项目信息：{}", examineSetupItemVO);
                examineSetupItemsVO.add(examineSetupItemVO);
            }
        };
        return examineSetupItemsVO;

    }

    @Override
    public PrepareScoreVO prepareScore(Integer itemId) {
        log.info("评分前的信息展示");

        //拷贝基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        PrepareScoreVO prepareScoreVO = new PrepareScoreVO();
        BeanUtils.copyProperties(item,prepareScoreVO );
        // 找到指导教师和负责任的userid 以及到用户表当中找到对应的名字
        String conduserid = item.getConduserid();
        String prinuserid = item.getPrinuserid();
        String condName = userMapper.getNameByUserId(conduserid);
        String prinName = userMapper.getNameByUserId(prinuserid);
        prepareScoreVO .setCondName(condName);
        prepareScoreVO.setPrinName(prinName);
        return prepareScoreVO;


    }

    /**
     * 对等待立项审核的项目评分
     * @param examineScoreDTO
     * @return
     */
    @Transactional
    @Override
    public void scoreSetupItem(ExamineScoreDTO examineScoreDTO) {
        Integer itemId = examineScoreDTO.getItemId();
        Integer avgScore = examineScoreDTO.getAvgScore();
        String failReason = examineScoreDTO.getFailReason();


        //先判断是否是失败
        if(avgScore<60){
            log.info("项目id为{}，评分为{}，失败原因为{}",itemId,avgScore,failReason);
            //项目立项审核失败 需要插入立项失败不通过评价 以及修改项目表当中状态
            setItemFailureMapper.insertFailure(itemId,failReason);
            String status = "立项驳回";
            itemMapper.updateItemStatus(itemId,status);
        }else{
            String status = "未中期审核";
            String commitLog="提交大创日志1次";
            String examLog="审核次数为1次";
            itemMapper.updateLog(itemId,commitLog,examLog);
            itemMapper.updateItemStatus(itemId,status);
        }
        String setupEnd = timeMapper.getSetupEndTime(1);
        String date = new Date().toString();
        if (setupEnd.compareTo(date)>0){
            throw new BaseException("申报时间已经截至");
        }

    }
    /**
     * 获取需要审核进展记录的项目
     * @return
     */
    @Override
    public ExamineProgressItemsVO getExamineProgressItems() {

        log.info("获取需要进行审核进展记录的项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)
        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);
        ExamineProgressItemsVO examineProgressItemsVO=new ExamineProgressItemsVO();
        //遍历每一个item_id，查询出项目对应的基本信息


        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("立项")) {
                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师信息
                log.info("开始遍历每一个项目id{}", itemId);
                Item item = itemMapper.getItemByItemId(itemId);
                ExamineProgressItemVO examineProgressItemVO = new ExamineProgressItemVO();

                BeanUtils.copyProperties(item, examineProgressItemVO);

                log.info("输出查询到的项目信息：{}", examineProgressItemVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                examineProgressItemVO.setPrinName(prinName);
                examineProgressItemVO.setCondName(condName);

                log.info("输出查询到的项目信息：{}", examineProgressItemVO);
                examineProgressItemsVO.add(examineProgressItemVO);
            }
        };
        return examineProgressItemsVO;

    }

    /**
     * 需要中期审核的项目
     * @return
     */
    @Override
    public ExamineMidItermsVO getExamineMidterms() {
        log.info("获取需要中期审核的项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)

        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        ExamineMidItermsVO examineMidItermsVO=new ExamineMidItermsVO();



        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("中期")){
                ExamineMidItermVO examineMidItermVO = new ExamineMidItermVO();

                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师的名字和项目下的所有成员
                Item item = itemMapper.getItemByItemId(itemId);
                BeanUtils.copyProperties(item,examineMidItermVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                examineMidItermVO.setPrinName(prinName);
                examineMidItermVO.setCondName(condName);
                log.info("输出查询到的项目信息：{}",examineMidItermVO);
                //现在去 用户 项目关系表中找到该项目下的所有成员
                List<String> userids= userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
                List<String> names=new ArrayList<>();
                for (String userid1:userids){
                    names.add(userMapper.getNameByUserId(userid1));
                }
                examineMidItermVO.setNames(names);
                log.info("输出查询到的项目信息：{}",examineMidItermVO);
                examineMidItermsVO.add(examineMidItermVO);
            }
        };


        return examineMidItermsVO;
    }

    /**
     * 准备审核中期项目
     * @param itemId
     * @return
     */
    @Override
    public PrepareMiditemVO prepareMiditem(Integer itemId) {
        log.info("准备审核中期项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)
        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);
        // 首先获取到项目基本信息
        Item item = itemMapper.getItemByItemId(itemId);
        PrepareMiditemVO prepareMiditemVO=new PrepareMiditemVO();
        BeanUtils.copyProperties(item,prepareMiditemVO);

        //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
        String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
        String conduserid = itemMapper.getConduseridByItemId(itemId);
        String prinName = userMapper.getNameByUserId(prinuserid);
        String condName = userMapper.getNameByUserId(conduserid);
        prepareMiditemVO.setPrinName(prinName);
        prepareMiditemVO.setCondName(condName);
        log.info("输出查询到的项目信息：{}",prepareMiditemVO);

        // 现在去 用户 项目关系表中找到该项目下的所有成员
        //现在去 用户 项目关系表中找到该项目下的所有成员
        List<String> userids= userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
        List<UserMainVO> userMainVOs=new ArrayList<>();
        for (int i = 0; i < userids.size(); i++) {
            //获取到项目下的其他成员的user对象 是成员
            UserMainVO userMainVO=new UserMainVO();
            log.info("项目下的其他成员的userid为："+userids.get(i));
            User user=userMapper.getByUserId(userids.get(i));
            BeanUtils.copyProperties(user,userMainVO);
            String work = userItemRelaMapper.getWorkByItemidWithUserid(itemId, userids.get(i));
            userMainVO.setWork(work);
            userMainVOs.add(userMainVO);
        }
        prepareMiditemVO.setPeoples(userMainVOs);

        return prepareMiditemVO;
    }

    /**
     * 对等待中期审核的项目评分
     * @param examineScoredto
     * @return
     */
    @Transactional
    @Override
    public void scoreMidItem(ExamineScoreDTO examineScoredto) {
        Integer itemId = examineScoredto.getItemId();
        Integer avgScore = examineScoredto.getAvgScore();
        String failReason = examineScoredto.getFailReason();


        //先判断是否是失败
        if(avgScore<60){
            log.info("项目id为{}，评分为{}，失败原因为{}",itemId,avgScore,failReason);
            //项目立项审核失败 需要插入立项失败不通过评价 以及修改项目表当中状态
            midItemFailureMapper.insertFailure(itemId,failReason);
            String status = "中期审核未通过";
            itemMapper.updateItemStatus(itemId,status);
        }else{
            String status = "未终项审核";
            String commitLog="提交大创日志2次";
            String examLog="审核次数为2次";
            itemMapper.updateLog(itemId,commitLog,examLog);
            itemMapper.updateItemStatus(itemId,status);
        }
        String midTimeEnd = timeMapper.getMiditemEndTime(1);
        String date = new Date().toString();
        if (midTimeEnd.compareTo(date)>0){
            throw new BaseException("中期阶段已经过了");
        }
    }

    /**
     * 准备下载文件
     * @return
     */
    @Override
    public DownloadFilesVO prepareDownloadFiles() {
        log.info("准备下载文件");

        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)
        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        DownloadFilesVO downloadFilesVO=new DownloadFilesVO();

        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){

                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师信息
                Item item = itemMapper.getItemByItemId(itemId);
                item.getCreateTime();
                log.info("开始遍历每一个项目id{}", itemId);
                DownloadFileVO downloadFileVO = new DownloadFileVO();
                BeanUtils.copyProperties(item,downloadFileVO);
                log.info("输出查询到的项目信息：{}", downloadFileVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                downloadFileVO.setPrinName(prinName);
                downloadFileVO.setPrinuserid(prinuserid);
                log.info("输出查询到的项目信息：{}", downloadFileVO);
                downloadFilesVO.add(downloadFileVO);

        };
        return downloadFilesVO;

    }

    /**
     * 根据格式下载文件
     * @param typeDownloadFileDTO
     * @return
     */
    @Override
    public FileMainsVO downloadFiles(TypeDownloadFileDTO typeDownloadFileDTO) {
        log.info("根据格式下载文件");
        FileMainsVO fileMainsVO=new FileMainsVO();
        List<FileMainVO> fileMainVOS=fileMapper.queryByDTO(typeDownloadFileDTO);
        log.info("根据格式下载文件，查询到的{}",fileMainVOS);
        fileMainsVO.setFileMainsVOS(fileMainVOS);

        return fileMainsVO;
    }

    /**
     * 需要结项审核的项目
     * @return
     */
    @Override
    public ExamineCompletedItemsVO getCompeletedIterms() {
        log.info("获取需要结项审核的项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)

        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        ExamineCompletedItemsVO examineCompletedItemsVO =new ExamineCompletedItemsVO();

        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("结项")){
                ExamineCompletedItemVO examineCompletedItermVO = new ExamineCompletedItemVO();

                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师的名字和项目下的所有成员
                Item item = itemMapper.getItemByItemId(itemId);
                BeanUtils.copyProperties(item,examineCompletedItermVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                examineCompletedItermVO.setPrinName(prinName);
                examineCompletedItermVO.setCondName(condName);
                log.info("输出查询到的项目信息：{}",examineCompletedItermVO);
                //现在去 用户 项目关系表中找到该项目下的所有成员
                List<String> userids= userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
                List<String> names=new ArrayList<>();
                for (String userid1:userids){
                    names.add(userMapper.getNameByUserId(userid1));
                }
                examineCompletedItermVO.setNames(names);
                log.info("输出查询到的项目信息：{}",examineCompletedItermVO);
                examineCompletedItemsVO.add(examineCompletedItermVO);
            }
        };


        return examineCompletedItemsVO;

    }

    /**
     * 对等待结项审核的项目评分
     * @param examineScoreDTO
     * @return
     */
    @Override
    public void scoreCompletedItem(ExamineScoreDTO examineScoreDTO) {
        Integer itemId = examineScoreDTO.getItemId();
        Integer avgScore = examineScoreDTO.getAvgScore();
        String failReason = examineScoreDTO.getFailReason();


        //先判断是否是失败
        if(avgScore<60){
            log.info("项目id为{}，评分为{}，失败原因为{}",itemId,avgScore,failReason);
            //项目结项审核失败 需要插入结项失败不通过评价 以及修改项目表当中状态
            compeletedItemFailureMapper.insertFailure(itemId,failReason);
            String status = "结项审核未通过";
            itemMapper.updateItemStatus(itemId,status);
        }else{
            String status = "结项审核通过";
            String commitLog="提交大创日志3次";
            String examLog="审核次数为3次";
            itemMapper.updateLog(itemId,commitLog,examLog);
            itemMapper.updateItemStatus(itemId,status);
        }
        String completedTimeEnd = timeMapper.getCompletedEndTime(1);
        String date = new Date().toString();
        if (completedTimeEnd.compareTo(date)>0){
            throw new BaseException("结项截至阶段已经过了");
        }

    }

    /**
     * 对等待延期结项审核的项目评分
     * @param examineScoreDTO
     * @return
     */
    @Override
    public void scoreDelayItem(ExamineScoreDTO examineScoreDTO) {
        Integer itemId = examineScoreDTO.getItemId();
        Integer avgScore = examineScoreDTO.getAvgScore();
        String failReason = examineScoreDTO.getFailReason();


        //先判断是否是失败
        if(avgScore<60){
            log.info("项目id为{}，评分为{}，失败原因为{}",itemId,avgScore,failReason);
            //项目延期结项审核失败 需要插入延期结项失败不通过评价 以及修改项目表当中状态
            delayItemMapper.insertDelayFailItem(itemId,failReason);
            String status = "延期结项审核未通过";
            itemMapper.updateItemStatus(itemId,status);
        }else{
            String status = "延期结项审核通过";
            itemMapper.updateItemStatus(itemId,status);
        }
    }

    /**
     * 需要延期结项审核的项目
     * @return
     */
    @Override
    public ExamineDelayItemsVO getDelayitems() {
        log.info("获取需要延期结项审核的项目");
        //获取当前登录的userid(在设置拦截器时，将usrid设置到 BaseContext的ThreadLocal中)

        Long id= BaseContext.getCurrentId();
        String userid=String.valueOf(id);
        log.info("当前用户号为{}",userid);

        //根据userid 到用户项目关系表里查询出所有的item_id
        List<Integer> itemslist = userItemRelaMapper.getItemsByUserId(userid);
        log.info("根据用户号查询用户所拥有的项目，用户号为{}，项目为{}",userid,itemslist);

        //遍历每一个item_id，查询出项目对应的基本信息
        ExamineDelayItemsVO examineDelayItemsVO =new ExamineDelayItemsVO();


        log.info("开始遍历每一个项目id");
        for(Integer itemId:itemslist){
            String itemStatus = itemMapper.getItemStatus(itemId);
            if(itemStatus.contains("延期")){
                ExamineDelayItemVO examineDelayItemVO=new ExamineDelayItemVO();


                //根据当前item_id 查询出项目对应的基本信息 此时还剩余 负责人指导教师的名字和项目下的所有成员
                Item item = itemMapper.getItemByItemId(itemId);
                BeanUtils.copyProperties(item,examineDelayItemVO);

                //现在是根据itemid 去查询项目表当中对应的负责人和指导教师的userid
                String prinuserid = itemMapper.getPrinuseridByItemId(itemId);
                String conduserid = itemMapper.getConduseridByItemId(itemId);
                String prinName = userMapper.getNameByUserId(prinuserid);
                String condName = userMapper.getNameByUserId(conduserid);
                examineDelayItemVO.setPrinName(prinName);
                examineDelayItemVO.setCondName(condName);
                log.info("输出查询到的项目信息：{}",examineDelayItemVO);
                //现在去 用户 项目关系表中找到该项目下的所有成员
                List<String> userids= userItemRelaMapper.getUseridsByItemidWithRole(itemId, 2);
                List<String> names=new ArrayList<>();
                for (String userid1:userids){
                    names.add(userMapper.getNameByUserId(userid1));
                }
                examineDelayItemVO.setNames(names);
                log.info("输出查询到的项目信息：{}",examineDelayItemVO);
                examineDelayItemsVO.add(examineDelayItemVO);
            }
        };


        return examineDelayItemsVO;

    }


}
